﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using QueueLoad.controls;

namespace QueueLoad
{
    /// <summary>
    /// 顺序，倒序异步加载一组图片(by 菩提树下的杨过 http://yjmyzz.cnblogs.com/)
    /// </summary>
    public partial class MainPage : Window
    {
        Stack<string> _imgStack = new Stack<string>();//如要倒序加载，换成 Queue<string>
       
        WebClient _wc = new WebClient();

        public MainPage()
        {
            InitializeComponent();

            _imgStack.Push("http://news.softpedia.com/images/news2/Silverlight-3-SDK-Updated-2.jpg");
            _imgStack.Push("http://i1-news.softpedia-static.com/images/news2/Silverlight-4-RTW-Set-for-April-15-2010-2.jpg");
            _imgStack.Push("http://www.newearthonline.co.uk/images/custom/silverlight.png");
            //_imgStack.Push("Gallery/Scenes/4.jpg");
            //_imgStack.Push("Gallery/Scenes/5.jpg");
            //_imgStack.Push("Gallery/Scenes/6.jpg");

            _wc.OpenReadCompleted += _wc_OpenReadCompleted;
        }

        void _wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                BitmapImage _bitMap = new BitmapImage();
               // _bitMap.StreamSource=e.Result;
                _bitMap.BeginInit();

                _bitMap.StreamSource = e.Result;
                _bitMap.EndInit();
                ImageItemBase _itemBase = e.UserState as ImageItemBase;
                _itemBase.img.Height = 200;
                _itemBase.img.Width = 200;
                _itemBase.img.Source = _bitMap;
                _itemBase.img.Visibility = Visibility.Visible;
                _itemBase.loading.Visibility = Visibility.Collapsed;

                LoadImage();//关键，继续加载下一个(是不是有点ajax中http长连接的意思，呵)

            }
        }

        private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            LoadImage();
        }


        void LoadImage()
        {
            if (_imgStack != null && _imgStack.Count > 0)
            {
                ImageItemBase _itemBase = new ImageItemBase();
                _itemBase.loading.Visibility = Visibility.Visible;
                _itemBase.img.Visibility = Visibility.Collapsed;

                imgContainer.Children.Add(_itemBase);

                Uri _imgUri = new Uri(_imgStack.Pop());
                _wc.OpenReadAsync(_imgUri, _itemBase);
            }
        }
    }
}
